package com.wang.users.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.util.DateUtil;
import com.wang.common.util.RegexUtil;
import com.wang.common.pojo.BasePojoEnum;
import com.wang.common.util.BeanUtil;
import com.wang.users.mapper.AtUsersMoveMapper;
import com.wang.users.pojo.AtUsersDesc;
import com.wang.users.pojo.AtUsersDescQuery;
import com.wang.users.pojo.AtUsersLeaveQuery;
import com.wang.users.pojo.AtUsersMove;
import com.wang.users.pojo.AtUsersMoveEnum;
import com.wang.users.pojo.AtUsersMoveQuery;
import com.wang.users.pojo.AtUsersOrgan;
import com.wang.users.service.AtUsersDescService;
import com.wang.users.service.AtUsersMoveService;
import com.wang.users.service.AtUsersOrganService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 针对表【at_demo_dynasty(示例_朝代表)】的数据库操作Service实现
 *
 * @author ZjxMi
 */
@Service
public class AtUsersMoveServiceImpl extends ServiceImpl<AtUsersMoveMapper, AtUsersMove>
        implements AtUsersMoveService {

    @Autowired
    private BeanUtil beanUtil;
    @Autowired
    private RegexUtil regexUtil;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private AtUsersOrganService usersOrganService;
    @Autowired
    private AtUsersDescService usersDescService;

    /**
     * 生成单号
     * @return
     */
    private String proccedRandSn(){
        String timeStr = this.dateUtil.dateToStr(new Date(), DateUtil.DATETIME_ALL_FORMAT);
        String randStr = this.regexUtil.randStr("2", 5);
        return AtUsersLeaveQuery.NO_PRE_STR + timeStr + randStr;
    }

    /**
     * model2: jsp --> servlet -->service --> dao --> db, 我们自己封装了一个 PageInfoUtil;
     * MybatisPlus: 不再需要调用 PageInfoUtil,老代码改造的时候是为了整合代码,如果没有老代码,直接写的新代码,采用下面的方式来搞
     *
     * @param page
     * @param query 查询对象
     * @return
     */
    @Override
    public List<AtUsersMove> findList(IPage<AtUsersMove> page, AtUsersMoveQuery query) {
        if (page != null) {
            return this.baseMapper.findList(page, query);
        }
        return this.baseMapper.findList(query);
    }

    @Override
    public AtUsersMove findOne(AtUsersMoveQuery query) {
        AtUsersMove one = this.baseMapper.findOne(query);
        if (Objects.nonNull(one)) {
            if (StringUtils.isNotEmpty(one.getOrganIdNew())) {
                AtUsersOrgan organObj = this.usersOrganService.findTreeList(one.getOrganIdNew());
                one.setOrganNewObj(organObj);
            }
        }
        return one;
    }

    @Override
    public int updateBatch(AtUsersMoveQuery query) {
        return this.baseMapper.updateBatch(query);
    }

    @Override
    public int deleteBatch(AtUsersMoveQuery query) {
        return this.baseMapper.deleteBatch(query);
    }

    /**
     * 对数据额外处理(非用户填写的数据)
     * @param entity
     */
    private void proccedUpdateData(AtUsersMove entity){
        if (Objects.isNull(entity.getCreateTime())) {
            entity.setCreateTime(new Date());
        }
        entity.setUpdateTime(new Date());
        /* 判断对象是否为空 */
        if (Objects.isNull(entity.getPubTime())) {
            entity.setPubTime(new Date());
        }
    }

    @Override
    public boolean save(AtUsersMove entity) {
        this.proccedUpdateData(entity);
        /* 新增加的记录默认未删除 */
        entity.setDelFlag(BasePojoEnum.DELFLAG_YES.getCode());
        entity.setExecStatus(BasePojoEnum.EXECUTE_NO.getCode());
        String sn = this.proccedRandSn();
        entity.setMoveNo(sn);
        return super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(AtUsersMove entity) {
        /* 先根据id查询数据库的内容; */
        AtUsersMoveQuery paramQuery = new AtUsersMoveQuery();
        AtUsersMove entityParam = paramQuery.getEntity();
        entityParam.setId(entity.getId());
        /* 数据库中查询的结果 */
        AtUsersMove oneDbResult = this.findOne(paramQuery);
        oneDbResult.setUsersDescObj(null);
        oneDbResult.setOrganNewObj(null);
        oneDbResult.setAuditObj(null);
        /*
        * 源对象和目标对象是一个类型(10个字段)
        * 源对象有5个字段有值,目标对象是10个有值
        * 把源对象中的5个字段有值,赋值到目标对象中.(覆盖)
        * */
        oneDbResult = (AtUsersMove) this.beanUtil.copy(entity, oneDbResult);

        this.proccedUpdateData(oneDbResult);
        boolean dbFlag = super.updateById(oneDbResult);
        if (dbFlag) {
            if (AtUsersMoveEnum.STATUSNEW_SHTG.getCode().equalsIgnoreCase(oneDbResult.getStatus())
                && oneDbResult.getMoveDate().before(new Date())) {
                /* 审核通过,查询用户更换组织 */
                AtUsersDescQuery paramUsersQuery = new AtUsersDescQuery();
                AtUsersDesc entityUsers = paramUsersQuery.getEntity();
                entityUsers.setId(oneDbResult.getUsersId());
                AtUsersDesc usersDb = this.usersDescService.findOne(paramUsersQuery);
                if (usersDb != null) {
                    if (!usersDb.getOrganId().equalsIgnoreCase(oneDbResult.getOrganIdNew())) {
                        usersDb.setOrganId(oneDbResult.getOrganIdNew());
                        this.usersDescService.updateById(usersDb);

                        oneDbResult.setExecStatus(BasePojoEnum.EXECUTE_YES.getCode());
                        this.updateById(oneDbResult);
                    }
                }
            }
        }
        return dbFlag;
    }
}